package com.example.bomc.security;

import com.example.bomc.service.userService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @ClassName：SecurityConfig
 * @Desctipyion：TODO
 * @Author：liangli
 * @Date：2021/4/28 19:17
 * @Version：1.0.0
 */
@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //        auth.inMemoryAuthentication().withUser("user")
        //                .password("{noop}123") // {noop}
        //                .roles("USER");
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/toLogin", "/css/**", "/js/**").permitAll().antMatchers("/**").hasAnyRole("ROLE_V1", "ROLE_V2", "ROLE_V3").anyRequest().authenticated()
                .and().formLogin()
                .loginProcessingUrl("/login").successForwardUrl("/index")
                .failureForwardUrl("/failer.html").permitAll().and().logout().logoutUrl("/logout")
                .logoutSuccessUrl("/toLogin").invalidateHttpSession(true).permitAll().and().csrf().disable();
    }
}
